// 登录与注册的模块
import {
    reqGetCode,
    reqUserRegister,
    reqUserLogin,
    reqUserInfo,
    reqLogOut
} from '@/api'
import {
    setToken,
    getToken,
    removeToken
} from '@/utils/token'
const state = {
    code: '',
    token: getToken(),
    userinfo: {}
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userinfo) {
        state.userinfo = userinfo
    },
    CLEARUSER(state) {
        state.token = ''
        state.userinfo = {}
        removeToken()
    }

}
const actions = {
    async getCode({
        commit
    }, phone) {
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit("GETCODE", result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegister({
        commit
    }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            console.log('输出一下啊');
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户登录
    async userLogin({
        commit
    }, data) {
        let result = await reqUserLogin(data)

        if (result.code == 200) {
            commit("USERLOGIN", result.data.token)
            // 本地存储
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    // 获取用户信息
    async getUserInfo({
        commit
    }) {
        let result = await reqUserInfo();
        if (result.code == '200') {
            commit('GETUSERINFO', result.data)
            return 'ok'
        }
    },
    // 退出登录
    async userLogout({
        commit
    }) {
        // 通知服务器清除token
        let result = await reqLogOut()
        console.log(result)
        if (result.code == 200) {
            // action不能操作state
            console.log('清除了');
            commit('CLEARUSER')
            return 'oke'
        } else {
            return Promise.reject(new Error("faile"))
        }
    }
}
const getters = {

}
export default {
    state,
    mutations,
    actions,
    getters
}